let db=require('../db/dbmanager');
const log4js        = require('../utils/logUtils');
const logger        = log4js.getLogger('model');

/**
 * 子通道数据库操作
 */
const TAG = "[Channel Model]";
let Channel={
    calcMediaUrl:  function (hostModel, parentid, deviceid, types, app, recordPath='') {
        const streamId = `${parentid}_${deviceid}`;
        const recordPathStr = recordPath?'record/':'';
        // logger.info(TAG, '计算地址', hostModel,streamId, parentid, deviceid);
        let str;
        switch (types) {
            case 'hls':
                str = `${hostModel.url}${recordPathStr}${app}/${streamId}/hls.m3u8`;
                break;
            case 'hlsTls':
                str = `${hostModel.urlTls}${recordPathStr}${app}/${streamId}/hls.m3u8`;
                break;
            case 'local':
                str = `${hostModel.rtmp_snap}${recordPathStr}${app}/${streamId}`;
                break;
            case 'flv':
                str = `${hostModel.url}${recordPathStr}${app}/${streamId}${recordPath}.live.flv`;
                break;
            case 'flvTls':
                str = `${hostModel.urlTls}${recordPathStr}${app}/${streamId}${recordPath}.live.flv`;
                break;
            case 'rtmp_snap':
                str = `${hostModel.rtmp_snap}${recordPathStr}${app}/${streamId}`;
                break;
            default:
                str = `${hostModel.rtmp}${recordPathStr}${app}/${streamId}`;
                break;
        }
        return str;
    },
    generateUrl(hostModel, item, app, recordPath=''){
        item.hls =  this.calcMediaUrl(hostModel, item.deviceid, item.channel_id, 'hls', app,recordPath);
        item.hlsTls =  this.calcMediaUrl(hostModel, item.deviceid, item.channel_id, 'hlsTls', app,recordPath);
        item.rtmp =  this.calcMediaUrl(hostModel, item.deviceid, item.channel_id, 'rtmp', app,recordPath);
        item.flv =  this.calcMediaUrl(hostModel, item.deviceid, item.channel_id, 'flv', app,recordPath);
        item.flvTls =  this.calcMediaUrl(hostModel, item.deviceid, item.channel_id, 'flvTls', app,recordPath);
        return item;
    },
    updateOnline:function(parentId,deviceId,online){
        return new Promise(function (resolve, reject) {
            // 是否有记录，不存在 的话新增
            let sql = "SELECT * FROM CHANNEL WHERE parentid=$parentid";

            let newParam = {
                $parentid: parentId,
            };

            if(deviceId){
                sql += " AND deviceid=$deviceid  ";
                newParam.$deviceid = deviceId;
            }
            db.sqliteDB.all(sql, newParam, function (err, rows) {
                if (!err) {
                    // 更新
                    let newOrUpdateSql;
                    if (rows && rows.length) {
                        newOrUpdateSql = "UPDATE CHANNEL SET online=$online ";
                        if (online) {
                            newParam.$last_heart = (new Date()).getTime();
                            newOrUpdateSql += ", last_heart=$last_heart "
                        }
                        newOrUpdateSql += " WHERE  parentid=$parentid";
                        if(deviceId){
                            newOrUpdateSql += " AND deviceid=$deviceid";
                        }
                    } else {
                        newParam.$last_heart = (new Date()).getTime();
                        newOrUpdateSql = "INSERT INTO CHANNEL(deviceid, parentid,online,last_heart) VALUES ($deviceid,$parentid,$online,$last_heart)";
                    }
                    db.sqliteDB.run(newOrUpdateSql, Object.assign(newParam, {
                        $online: online
                    }));
                    resolve(rows)
                } else {
                    reject();
                }
            });
        });
    },
    // 更新截图
    updateSnap:function(snap, parentid, deviceid){
        return new Promise(function (resolve, reject) {
            // 是否有记录，不存在 的话新增
            const sql = "SELECT * FROM CHANNEL WHERE deviceid=$deviceid AND parentid=$parentid";
            let newParam = {
                $deviceid: deviceid,
                $parentid: parentid
            };
            db.sqliteDB.all(sql, newParam, function (err, rows) {
                if (!err) {
                    // 更新
                    let newsql;
                    if (rows && rows.length) {
                        newsql = "UPDATE CHANNEL SET snap=$snap " +
                            " WHERE deviceid=$deviceid AND parentid=$parentid";
                    }
                    db.sqliteDB.run(newsql, Object.assign(newParam, {
                        $snap: snap
                    }));
                    resolve(rows)
                } else {
                    reject();
                }
            });
        });
    },
    /**
     * 协议变更
     * @param {*} channelInfo
     */
    updateProtocol: function(channelInfo){

    },
    // 更新设备信息，如果记录不存在就自动新增
    updateDeviceInfo: function(channelInfo){

        return new Promise(function (resolve, reject) {
            if(!channelInfo){
                logger.error(TAG, 'channelInfo 为空');
                reject('参数为空');
                return;
            }else{
                // logger.info(TAG, '[更新通道] channelInfo=', channelInfo);
            }
            // 是否有记录，不存在 的话新增
            const sql = "SELECT * FROM CHANNEL WHERE deviceid=$deviceid AND parentid=$parentid";
            const parentid=channelInfo.ParentID?channelInfo.ParentID.toString():'';
            const $owner=channelInfo.Owner?channelInfo.Owner.toString():'';
            const $address = channelInfo.Address?channelInfo.Address.toString():'';
            const $registerway = channelInfo.RegisterWay?channelInfo.RegisterWay.toString():'';
            const $secrecy = channelInfo.Secrecy?channelInfo.Secrecy.toString():'';
            const $manufacture = channelInfo.Manufacturer?channelInfo.Manufacturer.toString():'';
            const $model = channelInfo.Model?channelInfo.Model.toString():'';
            const $name = channelInfo.Name?channelInfo.Name.toString():'';
            const $civilcode = channelInfo.CivilCode?channelInfo.CivilCode.toString():'';
            const $catalogtype = channelInfo.CatalogType?channelInfo.CatalogType.toString():'';
            const $online = channelInfo.Status?(channelInfo.Status.toString()==='ON'?1:0):1;
            let newParam = {
                $deviceid: channelInfo.DeviceID.toString(),
                $parentid: parentid
            };
            logger.info(TAG, sql, $online, channelInfo.Status, channelInfo.Status.toString());
            db.sqliteDB.all(sql, newParam, function (err, rows) {
                if (!err) {
                    // 更新
                    let newsql;
                    if (rows && rows.length) {
                        newsql = "UPDATE CHANNEL SET online=$online, " +
                            "name=$name," +
                            "manufacture=$manufacture," +
                            "model=$model," +
                            "owner=$owner," +
                            "civilcode=$civilcode," +
                            "address=$address," +
                            "registerway=$registerway," +
                            "secrecy=$secrecy," +
                            "last_heart=$last_heart," +
                            "rtsp_url=$rtsp_url," +
                            "catalogtype=$catalogtype "+
                            " WHERE deviceid=$deviceid AND parentid=$parentid";
                    } else {
                        // 新增
                        newsql = "INSERT INTO CHANNEL(deviceid,parentid,online,name,manufacture,model,owner,civilcode,address,registerway,secrecy,last_heart,rtsp_url,catalogtype) " +
                            " VALUES " +
                            "($deviceid,$parentid,$online,$name,$manufacture,$model,$owner,$civilcode,$address,$registerway,$secrecy,$last_heart,$rtsp_url,$catalogtype)";
                    }
                    const setValue = Object.assign(newParam, {
                        $name, $manufacture, $model, $owner, $civilcode,
                        $address, $registerway, $secrecy,
                        $last_heart: (new Date()).getTime(),
                        $rtsp_url: channelInfo.rtsp_url,
                        $catalogtype,$online
                    });
                    db.sqliteDB.run(newsql, setValue);
                    // logger.info(TAG, 'updatechannel debug', newsql,$online, setValue);
                    resolve(rows)
                } else {
                    logger.error(TAG, 'updatechannel error', $online);
                    reject();
                }
            });
        });
    },
    /**
     * 查询列表
     * @param {*} parentId
     */
    list: function(parentId){
        return new Promise(function (resolve) {
            const sql = `SELECT * FROM CHANNEL WHERE parentid='${parentId}'`;
            logger.info(TAG, `api查询列表, parentId=${parentId}`, sql);
            db.sqliteDB.queryData(sql, function (rows) {
                resolve(rows);
            });
        });
    },
    // TODO: 重置状态，camera的可能要修改
    reset:function(){
        let minTime = (new Date()).getTime()-60*60*1000;
        const sql = "UPDATE CHANNEL SET online=0 WHERE last_heart<" + minTime;
        logger.log(TAG, sql);
        db.sqliteDB.run(sql);
    },
    /**
     * 根据父通道删除所有子通道信息
     * @param {*} parentId
     */
    deleteByParentId: function(parentId){
        const sqlChannel="DELETE FROM CHANNEL WHERE parentid = $parentid";
        let paramChannel = {$parentid: parentId};
        db.sqliteDB.run(sqlChannel, paramChannel);
    },
    /**
     * 删除某个通道
     * @param parentId 设备id
     * @param deviceId 子通道
     */
    deleteByDeviceId: function(parentId, deviceId){
        const sqlChannel="DELETE FROM CHANNEL WHERE parentid = $parentId and deviceid=$deviceId";
        let paramChannel = {$parentId: parentId, $deviceId: deviceId};
        db.sqliteDB.run(sqlChannel, paramChannel);
    }
};
module.exports=Channel;
